﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Linq;
using Microsoft.Phone.Tasks;
using QuickTasks.ViewModels.Data;
using QuickTasks.ViewModels.Properties;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using QuickTasks.GeocodeService;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
using System.Windows.Navigation;
using LocalSettings;
using CommonControls;
using Microsoft.Phone.Net.NetworkInformation;
using QuickTasks.ViewModels.Tables;
using System.ComponentModel;
using System.Threading;
using Microsoft.Phone.Scheduler;
using local = QuickTasks;
using Microsoft.Phone.Shell;
using QuickTasks.ViewModels;
using AdRotator;
using Common.Library;






namespace QuickTasks
{
    public partial class MainPage : PhoneApplicationPage
    {

        #region Global
       
        string dis;

        QuickTasks.ViewModels.Data.Common objlogo = new QuickTasks.ViewModels.Data.Common();
        FavoritePeople objfavoritepeo = new FavoritePeople();
        QuickLinks objQuickLinks = new QuickLinks();
        QuickMessages objQuickMessages = new QuickMessages();
        ToDoListData objToDoListData = new ToDoListData();
        AddAddress objAddress = new AddAddress();
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        string LId=string.Empty;
       
        AboutUs about;
        QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString);
        #endregion

        #region constructor
        public MainPage()
        {

            InitializeComponent();
            RununderLock(settings);
            App.MainPanorama = this;
            imgLogo.Source = objlogo.LoadPanoramaLogo();
           
        }

        void backgroundworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                
                if (ListClass<FavoritePeopleProp>.Instance.list.Count >= 1)
                {
                    peopcanvas.Visibility = Visibility.Collapsed;
                }
                else
                {
                    peopcanvas.Visibility = Visibility.Visible;
                }

                lbxFavoritePeople.ItemsSource = ListClass<FavoritePeopleProp>.Instance.list;

                if (ListClass<ToDoListProper>.Instance.list.Count >= 1)
                {
                    taskcanvas.Visibility = Visibility.Collapsed;

                }
                else
                {
                    taskcanvas.Visibility = Visibility.Visible;
                }
                lbxToDoList.ItemsSource = ListClass<ToDoListProper>.Instance.list;

                if (ListClass<QuickLinkProp>.Instance.list.Count >= 1)
                {
                    linkscanvas.Visibility = Visibility.Collapsed;

                }
                else
                {
                    linkscanvas.Visibility = Visibility.Visible;
                }
                lbxQuickLinks.ItemsSource = ListClass<QuickLinkProp>.Instance.list;

                if (ListClass<QuickMessageProp>.Instance.list.Count >= 1)
                {
                    msgcanvas.Visibility = Visibility.Collapsed;

                }
                else
                {
                    msgcanvas.Visibility = Visibility.Visible;
                }
                lbxQuickMessages.ItemsSource = ListClass<QuickMessageProp>.Instance.list;
               
                ListClass<AddressProp>.Instance.list = objAddress.loadCityData(IsolatedSettings.getSettingsStringValue("DefaultPlace"));
                lbxAddresslist.ItemsSource = ListClass<AddressProp>.Instance.list;
                PanoramaMain.DefaultItem = PanoramaMain.Items[(int)properties.props];
             
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  backgroundworker_RunWorkerCompleted event In MainPage.xaml page", ex);
            }
        }

        void backgroundworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
               
                ListClass<ToDoListProper>.Instance.list = objToDoListData.LoadToDoListCity(IsolatedSettings.getSettingsStringValue("DefaultPlace"));
              
                ListClass<FavoritePeopleProp>.Instance.list = objfavoritepeo.LoadFavotitePeopleCities(IsolatedSettings.getSettingsStringValue("DefaultPlace"));
               
                ListClass<QuickLinkProp>.Instance.list = objQuickLinks.LoadLinksDetailsSameData(IsolatedSettings.getSettingsStringValue("DefaultPlace"));
               
                ListClass<QuickMessageProp>.Instance.list = objQuickMessages.LoadFavotitePeopleCitiesSameData(IsolatedSettings.getSettingsStringValue("DefaultPlace"));
                
   
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  backgroundworker_DoWork event In MainPage.xaml page", ex);
            }
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
           
            properties.props = PanoramaMain.SelectedIndex;

        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            var stack = NavigationService.BackStack;
            while (stack.Count() > 0)
            {
                NavigationService.RemoveBackEntry();
            }
        }

     
        private void loadPanoramaBackGrounds()
        {
            String Background = "";
            Background = QuickTasks.ViewModels.Data.Common.getSettingsValue("SelectedBackground");
            ImageBrush PanoramBrush = new ImageBrush();
            if (Background != "")
                PanoramBrush.ImageSource = new BitmapImage(new Uri(@"Images\BigPanoramaBgImages/" + Background, UriKind.Relative));
            PanoramaMain.Background = PanoramBrush;
        }

        #endregion

        #region PageLoad
       
  
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
          
            try
            {
              
                if (NetworkInterface.GetIsNetworkAvailable() && NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None && (!string.IsNullOrEmpty(IsolatedSettings.getSettingsStringValue("GeoLocationStatus1"))) && IsolatedSettings.getSettingsStringValue("GeoLocationStatus1") == "true")
                {
                    using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                    {
                        var loc1 = (from i in context.Loc orderby i.TableId descending select i).Take(1);
                        if (loc1.Count() >= 0)
                        {
                            foreach (var loc2 in loc1)
                            {
                                IsolatedSettings.saveSettings("DefaultPlace", loc2.id.ToString());
                              
                                break;
                            }
                        }
                    }
                }
               if(string.IsNullOrEmpty(IsolatedSettings.getSettingsStringValue("DefaultPlace")))
                   IsolatedSettings.saveSettings("DefaultPlace", "1");
                    LoadMethods();

                    if (App.AdStatus == false)
                    {
                        if (VisualTreeHelper.GetChildrenCount(Application.Current.RootVisual) > 0)
                        {
                            Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                            AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
                            Adc.Invalidate();
                            App.AdStatus = true;
                        }
                    }                 
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  PhoneApplicationPage_Loaded event In MainPage.xaml page", ex);
            }

        }

        public static string getSettingsstringValue(string keyname)
        {
            string keyvalue = string.Empty;
            try
            {

              
                var settings = IsolatedStorageSettings.ApplicationSettings;
                if (settings.Contains(keyname))

                    keyvalue = settings[keyname].ToString();

                return keyvalue;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  getSettingsstringValue method In MainPage.xaml page", ex);
                return keyvalue;
            }
        }


       
        public void LoadMethods()
        {
            BackgroundWorker backgroundworker = new BackgroundWorker();
            backgroundworker.DoWork += new DoWorkEventHandler(backgroundworker_DoWork);
            backgroundworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundworker_RunWorkerCompleted);
            backgroundworker.RunWorkerAsync();
            LoadPmBackgroung( IsolatedSettings.getSettingsStringValue("DefaultPlace"));
            
        }

        #endregion

        #region Todolist

        private void ThemeableToDoList_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (App.IsTrial)
                {
                    var todocount = from t in context.Todo select t;
                    if (todocount.Count() > 9)
                    {
                        MessageBoxResult resulttodo = MessageBox.Show("Buy full version to add more tasks.press ok to buy", "UPGRADE TO FULL VERSION", MessageBoxButton.OKCancel);
                        if (resulttodo == MessageBoxResult.OK)
                        {
                            MarketplaceDetailTask task = new MarketplaceDetailTask();
                            task.ContentType = MarketplaceContentType.Applications;
                            task.ContentIdentifier = "1003425a-0db9-445a-a2e7-6a36074573c5";
                            task.Show();
                        }
                    }
                    else
                    {
                        PhoneApplicationService.Current.State["isbacknav"] = false;
                        NavigationService.Navigate(new Uri("/Views/ToDoList/ToDoList.xaml", UriKind.Relative));
                        App.navigationstring = "";
                    }
                }
                else
                {
                    PhoneApplicationService.Current.State["isbacknav"] = false;
                    NavigationService.Navigate(new Uri("/Views/ToDoList/ToDoList.xaml", UriKind.Relative));

                    App.navigationstring = "";
                }
            }

            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  ThemeableToDoList_MouseLeftButtonDown event In MainPage.xaml page", ex);
            }
        }

        private void lbxToDoList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxToDoList.SelectedIndex == -1)
                    return;
                string listid = (lbxToDoList.SelectedItem as ToDoListProper).Id;
                IsolatedSettings.saveSettings("taskedit", "EDit");
                PhoneApplicationService.Current.State["state"] = false;
                NavigationService.Navigate(new Uri("/Views/ToDoList/ToDoList.xaml?listid=" + listid, UriKind.Relative));
                App.navigationstring = "";
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  lbxToDoList_SelectionChanged event In MainPage.xaml page", ex);
            }

        }

        #endregion

        #region Favorite People
        
        private void imgPersonal_Click(object sender, MouseButtonEventArgs e)
        {
            //call to mobile
            string id = "";
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxFavoritePeople.ItemContainerGenerator.ContainerFromItem((sender as FrameworkElement).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                id = (selectedListBoxItem.Content as FavoritePeopleProp).Id;
                objfavoritepeo.GetPhoneNumbers(id, "mobile");
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  imgPersonal_Click event In MainPage.xaml page", ex);
            }
        }

        private void imgHome_Click(object sender, MouseButtonEventArgs e)
        {
            //call to home
            string id = "";
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxFavoritePeople.ItemContainerGenerator.ContainerFromItem((sender as FrameworkElement).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                id = (selectedListBoxItem.Content as FavoritePeopleProp).Id;
                objfavoritepeo.GetPhoneNumbers(id, "home");
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  imgHome_Click event In MainPage.xaml page", ex);
            }
        }

        private void imgWork_Click(object sender, MouseButtonEventArgs e)
        {
            //call to work
            string id = "";
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxFavoritePeople.ItemContainerGenerator.ContainerFromItem((sender as FrameworkElement).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                id = (selectedListBoxItem.Content as FavoritePeopleProp).Id;
                objfavoritepeo.GetPhoneNumbers(id, "mwork");
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  imgWork_Click event In MainPage.xaml page", ex);
            }
        }

        private void imgPeopleSettings_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/BackGrounds/BackGrounds.xaml", UriKind.Relative));
            App.navigationstring = "";
        }

        #endregion

        #region Messages

        private void imgAddNewMessage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (App.IsTrial)
                {
                    var messagecount = from m in context.message select m;
                    if (messagecount.Count() > 9)
                    {
                        MessageBoxResult resultmessage = MessageBox.Show("Buy full version to add more messages.press ok to buy", "UPGRADE TO FULL VERSION", MessageBoxButton.OKCancel);
                        if (resultmessage == MessageBoxResult.OK)
                        {
                            MarketplaceDetailTask task = new MarketplaceDetailTask();
                            task.ContentType = MarketplaceContentType.Applications;
                            task.ContentIdentifier = "1003425a-0db9-445a-a2e7-6a36074573c5";
                            task.Show();
                        }
                    }
                    else
                    {
                        App.EmailId = "";
                        App.Mobile = "";
                        App.Subject = "";
                        App.Message = "";
                        NavigationService.Navigate(new Uri("/Views/Message/AddMessages.xaml", UriKind.Relative));
                        App.navigationstring = "";
                    }
                }
                else
                {
                    App.EmailId = "";
                    App.Mobile = "";
                    App.Subject = "";
                    App.Message = "";
                    NavigationService.Navigate(new Uri("/Views/Message/AddMessages.xaml", UriKind.Relative));
                    App.navigationstring = "";
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  imgAddNewMessage_MouseLeftButtonDown event In MainPage.xaml page", ex);
            }
        }



        #endregion

        #region Links

        private void imgAddNewLinks_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (App.IsTrial)
                {
                    var linkcount = from l in context.link select l;
                    if (linkcount.Count() > 9)
                    {
                        MessageBoxResult resultlink = MessageBox.Show("Buy full version to add more links.press ok to buy", "UPGRADE TO FULL VERSION", MessageBoxButton.OKCancel);
                        if (resultlink == MessageBoxResult.OK)
                        {
                            MarketplaceDetailTask task = new MarketplaceDetailTask();
                            task.ContentType = MarketplaceContentType.Applications;
                            task.ContentIdentifier = "1003425a-0db9-445a-a2e7-6a36074573c5";
                            task.Show();
                        }
                    }
                    else
                    {
                        NavigationService.Navigate(new Uri("/Views/Links/AddLinks.xaml", UriKind.Relative));
                        App.navigationstring = "";
                    }
                }
                else
                {
                    NavigationService.Navigate(new Uri("/Views/Links/AddLinks.xaml", UriKind.Relative));
                    App.navigationstring = "";
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  imgAddNewLinks_MouseLeftButtonDown  event In MainPage.xaml page", ex);
            }
        }

        private void imgLinkSettings_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Links/LinkSettings.xaml", UriKind.Relative));
            App.navigationstring = "";
        }

        private void lbxQuickLinks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxQuickLinks.SelectedIndex == -1)
                    return;
                string linkId = (lbxQuickLinks.SelectedItem as QuickLinkProp).Id;
                NavigationService.Navigate(new Uri("/Views/Browser/Browsers.xaml?linkId=" + linkId, UriKind.Relative));
                App.navigationstring = "";
                lbxQuickLinks.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  lbxQuickLinks_SelectionChanged  event In MainPage.xaml page", ex);
            }
        }

        #endregion

        #region Address

        private void imgAddAddress_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (App.IsTrial)
                {
                    var Addresscount = from a in context.Add select a;
                    if (Addresscount.Count() > 2)
                    {
                        MessageBoxResult resultadd = MessageBox.Show("Buy full version to add more places.press ok to buy", "UPGRADE TO FULL VERSION", MessageBoxButton.OKCancel);
                        if (resultadd == MessageBoxResult.OK)
                        {
                            MarketplaceDetailTask task = new MarketplaceDetailTask();
                            task.ContentType = MarketplaceContentType.Applications;
                            task.ContentIdentifier = "1003425a-0db9-445a-a2e7-6a36074573c5";
                            task.Show();
                        }
                    }
                    else
                    {
                        IsolatedSettings.saveSettings("type", "new");
                        NavigationService.Navigate(new Uri("/Views/Places/Address.xaml", UriKind.Relative));
                        App.navigationstring = "";
                    }
                }
                else
                {
                    IsolatedSettings.saveSettings("type", "new");
                    NavigationService.Navigate(new Uri("/Views/Places/Address.xaml", UriKind.Relative));
                    App.navigationstring = "";
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  imgAddAddress_MouseLeftButtonDown  event In MainPage.xaml page", ex);
            }
        }


        private void imgAddSettings_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Places/AddPlacesSettings.xaml", UriKind.Relative));
            App.navigationstring = "";
        }

        #endregion

        #region contextmenu

        private void MenuItemsetaslocatio_Click(object sender, RoutedEventArgs e)
        {
            string add = "";
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxAddresslist.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                string locid = (selectedListBoxItem.Content as AddressProp).Id;
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {
                    var addressid = from i in context.Add where i.id.ToString() == locid select i;
                    foreach (var loc in addressid)
                    {
                        App.lat = loc.latitude;
                        App.lon = loc.longitude;
                        add = loc.address;
                    }
                }

                BingMapsTask bmt = new BingMapsTask();
                bmt.SearchTerm = add;
                bmt.Show();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItemsetaslocatio_Click  event In MainPage.xaml page", ex);
            }

        }

        #endregion
        private static void RununderLock(IsolatedStorageSettings settings)
        {
            bool AppLevelState = true;
            if (settings.Contains("AppLevelState"))
                AppLevelState = Convert.ToBoolean(settings["AppLevelState"]);

            if (AppLevelState == true)
            {
                MessageBoxResult resultLocService = MessageBox.Show("In order to deliver location tracking services, Quick Tasks needs permission to use the geo location services on the device. Without this permission location tracking would not be active when an activity is running. \n\n\n Do you want to allow Quick Tasks to use location service?", "Location Service", MessageBoxButton.OKCancel);
                if (resultLocService == MessageBoxResult.OK)
                {
                    SettingsHelper.Save("GeoLocationStatus", "true");
                    bool enabled = true;
                    GeoCoordinateWatcher geo = new GeoCoordinateWatcher();
                    geo.Start();
                    if (geo.Permission == GeoPositionPermission.Denied)
                    {
                        enabled = false;
                    }
                    geo.Stop();
                    geo.Dispose();


                    MessageBoxResult resultRunUnderLock = MessageBox.Show("In order to deliver tracking services Quick Tasks needs permission to run under the phone's locked screen. Without this permission tracking services will be suspended whenever display gets locked. \n\n\n Do you want to allow Quick Tasks to run during screen locks?", "Run Under Lock Screen", MessageBoxButton.OKCancel);

                    if (resultRunUnderLock == MessageBoxResult.OK)
                    {
                        ApplicationIdleModeHelper.Current.HasUserAgreedToRunUnderLock = true;
                        SettingsHelper.Save("runUnderLock", "true");
                    }
                    else
                        SettingsHelper.Save("runUnderLock", "false");
                }
                else
                    SettingsHelper.Save("GeoLocationStatus", "false");

                SettingsHelper.Save("AppLevelState", "false");
            }
        }
        private void MenuItemsetasbackground_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxAddresslist.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                string placeid = (selectedListBoxItem.Content as AddressProp).Id;
                NavigationService.Navigate(new Uri("/Views/BackGrounds/BackGrounds.xaml?Placeid=" + placeid, UriKind.Relative));
                App.navigationstring = "";
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItemsetasbackground_Click  event In MainPage.xaml page", ex);
            }
        }


        private void LoadPmBackgroung(string id)
        {
            try
            {
                IsolatedStorageFile isostore = IsolatedStorageFile.GetUserStoreForApplication();
                string Image = "";
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {
                    var ActToDel = from t in context.back
                                   where t.id.ToString() == id
                                   select t;
                    if (ActToDel.Count() > 0)
                    {
                        foreach (var acte in ActToDel)
                        {
                            if (acte.name != null)
                            {
                                Image = acte.name;
                            }
                            if (Image == "18.jpg")
                            {
                                PanoramaMain.Background = new SolidColorBrush(Colors.Black);
                            }
                            else
                            {
                                ImageBrush PanoramBrush = new ImageBrush();
                                BitmapImage bi = new BitmapImage();
                                if (isostore.FileExists(Image))
                                {
                                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                                    {
                                        using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(Image, FileMode.Open, FileAccess.Read))
                                        {
                                            bi.SetSource(fileStream);
                                        }
                                    }
                                    PanoramBrush.ImageSource = bi;
                                    PanoramaMain.Background = PanoramBrush;
                                }

                                else
                                {
                                    PanoramBrush.ImageSource = new BitmapImage(new Uri(@"Images\BigPanoramaBgImages/" + Image, UriKind.Relative));
                                    PanoramaMain.Background = PanoramBrush;

                                }
                            }
                        }
                    }
                    else
                    {
                        PanoramaMain.Background = new SolidColorBrush(Colors.Black);
                    }

                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  LoadPmBackgroung  method In MainPage.xaml page", ex);
            }
        }


        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxAddresslist.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                LId = (selectedListBoxItem.Content as AddressProp).Id;
                IsolatedSettings.saveSettings("type", "Edit");
                NavigationService.Navigate(new Uri("/Views/Places/Address.xaml?Id=" + LId, UriKind.Relative));
                App.navigationstring = "";
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItem_Click  event In MainPage.xaml page", ex);
            }

        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxAddresslist.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                string id = (selectedListBoxItem.Content as AddressProp).Id;
                MessageBoxResult resultLocService = MessageBox.Show("Deleting this Place makes all Contacts in this place as Global. Are you sure you want to Delete it.", "Delete Place", MessageBoxButton.OKCancel);
                if (resultLocService == MessageBoxResult.OK)
                {
                    using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                    {
                        IQueryable<QuickTasks.ViewModels.Tables.Address> addressid = from i in context.Add where i.id.ToString() == id select i;
                        QuickTasks.ViewModels.Tables.Address add = addressid.FirstOrDefault();
                        context.Add.DeleteOnSubmit(add);
                        context.SubmitChanges();

                        var favid = from i in context.people where i.place == id select i;

                        foreach (var rep in favid)
                        {
                            rep.place = "1";
                        }
                        context.SubmitChanges();

                        var Todoid = from i in context.Todo where i.place == id select i;

                        foreach (var rep in Todoid)
                        {
                            rep.place = "1";
                        }
                        context.SubmitChanges();

                        var linkid = from i in context.link where i.place == id select i;

                        foreach (var rep in linkid)
                        {
                            rep.place = "1";
                        }

                        context.SubmitChanges();

                        var mesid = from i in context.message where i.place == id select i;

                        foreach (var rep in mesid)
                        {
                            rep.place = "1";
                        }
                        context.SubmitChanges();

                        var plaid = from i in context.back where i.id.ToString() == id select i;

                        foreach (var rep in plaid)
                        {
                            rep.id = 1;
                        }
                        context.SubmitChanges();
                    }
                }

                IsolatedSettings.saveSettings("DefaultPlace", "1");

                LoadMethods();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItem_Click_1  event In MainPage.xaml page", ex);
            }
        }



        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            try
            {
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {
                    ListBoxItem selectedListBoxItem = this.lbxFavoritePeople.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                    if (selectedListBoxItem == null)
                        return;
                    string id = (selectedListBoxItem.Content as FavoritePeopleProp).Id;
                    IQueryable<people> addressid = from i in context.people where i.id.ToString() == id select i;
                    people p = addressid.FirstOrDefault();
                    context.people.DeleteOnSubmit(p);
                    context.SubmitChanges();
                }

                string DefaultPlace = "";
                if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                {
                    DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                }
                else
                {
                    DefaultPlace = "1";
                }
                ListClass<FavoritePeopleProp>.Instance.list = objfavoritepeo.LoadFavotitePeopleCities(DefaultPlace);
                lbxFavoritePeople.ItemsSource = ListClass<FavoritePeopleProp>.Instance.list;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItem_Click_3  event In MainPage.xaml page", ex);
            }
        }

        private void MenuItem_Click_4(object sender, RoutedEventArgs e)
        {
            try
            {
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {
                    ListBoxItem selectedListBoxItem = this.lbxQuickMessages.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                    if (selectedListBoxItem == null)
                        return;
                    string id = (selectedListBoxItem.Content as QuickMessageProp).Id;
                    IQueryable<messages> addressid = from i in context.message where i.id.ToString() == id select i;
                    messages mes = addressid.FirstOrDefault();
                    context.message.DeleteOnSubmit(mes);
                    context.SubmitChanges();
                }

                string DefaultPlace = "";
                if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                {
                    DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                }
                else
                {
                    DefaultPlace = "1";
                }
                ListClass<QuickMessageProp>.Instance.list = objQuickMessages.LoadFavotitePeopleCitiesSameData(DefaultPlace);
                lbxQuickMessages.ItemsSource = ListClass<QuickMessageProp>.Instance.list;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItem_Click_4  event In MainPage.xaml page", ex);
            }
        }

        private void MenuItem_Click_5(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxQuickLinks.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                string linkId = (selectedListBoxItem.Content as QuickLinkProp).Id;
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {
                    IQueryable<Links> lastLinkId = from i in context.link where i.id.ToString() == linkId select i;
                    Links link = lastLinkId.FirstOrDefault();
                    context.link.DeleteOnSubmit(link);
                    context.SubmitChanges();
                }

                string DefaultPlace = "";
                if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                {
                    DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                }
                else
                {
                    DefaultPlace = "1";
                }
                ListClass<QuickLinkProp>.Instance.list = objQuickLinks.LoadLinksDetailsSameData(DefaultPlace);
                lbxQuickLinks.ItemsSource = ListClass<QuickLinkProp>.Instance.list;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItem_Click_5  event In MainPage.xaml page", ex);
            }
        }

        private void MenuItem_Click_6(object sender, RoutedEventArgs e)
        {
            string reminderid = string.Empty;
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxToDoList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                string listid = (selectedListBoxItem.Content as ToDoListProper).Id;
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {

                    IQueryable<Todo> favoriteid = from i in context.Todo where i.id.ToString() == listid select i;
                    Todo todo = favoriteid.FirstOrDefault();
                    context.Todo.DeleteOnSubmit(todo);
                    context.SubmitChanges();
                    IQueryable<Reminders> reminder = from i in context.reminderalr where i.id.ToString() == listid select i;
                    if (reminder.Count() > 0)
                    {
                        foreach (var r in reminder)
                        {
                            reminderid = r.Rguid;
                            break;
                        }

                        if (ScheduledActionService.Find(reminderid) != null)
                        {
                            ScheduledActionService.Remove(reminderid);
                        }
                        Reminders rem = reminder.FirstOrDefault();
                        context.reminderalr.DeleteOnSubmit(rem);
                        context.SubmitChanges();
                    }
                }

                string DefaultPlace = "";
                if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                {
                    DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                }
                else
                {
                    DefaultPlace = "1";
                }

                ListClass<ToDoListProper>.Instance.list = objToDoListData.LoadToDoListCity(DefaultPlace);
                lbxToDoList.ItemsSource = ListClass<ToDoListProper>.Instance.list;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItem_Click_6  event In MainPage.xaml page", ex);
            }
        }

        private void MenuItem_Click_10(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxToDoList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                LId = (selectedListBoxItem.Content as ToDoListProper).Id;

                IsolatedSettings.saveSettings("taskedit", "EDit");
                PhoneApplicationService.Current.State["state"] = false;
                NavigationService.Navigate(new Uri("/Views/ToDoList/ToDoList.xaml?listid=" + LId, UriKind.Relative));
                App.navigationstring = "";
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItem_Click_10  event In MainPage.xaml page", ex);
            }
        }

        private void MenuItem_Click_8(object sender, MouseButtonEventArgs e)
        {
            try
            {
                IsolatedSettings.saveSettings("mtype", "Edit");
                var emp = ListClass<QuickMessageProp>.Instance.list.Where(a => a.Id.Equals(((System.Windows.FrameworkElement)(e.OriginalSource)).Tag)).ToList();
                foreach (var item in emp)
                {
                    NavigationService.Navigate(new Uri("/Views/Message/AddMessages.xaml?quickId=" + item.Id + "&quicktype=" + item.MessageType, UriKind.Relative));
                    App.navigationstring = "";
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItem_Click_8  event In MainPage.xaml page", ex);
            }
        }

        private void MenuItem_Click_9(object sender, MouseButtonEventArgs e)
        {
            try
            {
                var emp = ListClass<QuickMessageProp>.Instance.list.Where(a => a.Id.Equals(((System.Windows.FrameworkElement)(e.OriginalSource)).Tag)).ToList();
                foreach (var item in emp)
                {
                    if (item.MessageType == "SMS")
                    {
                        NavigationService.Navigate(new Uri("/Views/Message/SendSms.xaml?quickId=" + item.Id + "&quicktype=" + item.MessageType, UriKind.Relative));
                        App.navigationstring = "";

                    }
                    if (item.MessageType == "Email")
                    {
                        NavigationService.Navigate(new Uri("/Views/Message/SendEmail.xaml?quickId=" + item.Id + "&quicktype=" + item.MessageType, UriKind.Relative));
                        App.navigationstring = "";

                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItem_Click_9  event In MainPage.xaml page", ex);
            }

        }

        private void imgAddContacts_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (App.IsTrial)
                {
                    var peoplecount = from p in context.people select p;
                    if (peoplecount.Count() > 9)
                    {
                        MessageBoxResult resultpeople = MessageBox.Show("Buy full version to add more contacts.press ok to buy", "UPGRADE TO FULL VERSION", MessageBoxButton.OKCancel);
                        if (resultpeople == MessageBoxResult.OK)
                        {
                            MarketplaceDetailTask task = new MarketplaceDetailTask();
                            task.ContentType = MarketplaceContentType.Applications;
                            task.ContentIdentifier = "1003425a-0db9-445a-a2e7-6a36074573c5";
                            task.Show();
                        }
                    }
                    else
                    {
                        NavigationService.Navigate(new Uri("/Views/FavoritePeople/contacts.xaml", UriKind.Relative));
                        App.navigationstring = "";
                    }
                }
                else
                {
                    NavigationService.Navigate(new Uri("/Views/FavoritePeople/contacts.xaml", UriKind.Relative));
                    App.navigationstring = "";
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  imgAddContacts_MouseLeftButtonDown  event In MainPage.xaml page", ex);
            }

        }

        private void lbxFavoritePeople_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool check = false;
            if (lbxFavoritePeople.SelectedIndex == -1)
                return;

            string Id = (lbxFavoritePeople.SelectedItem as FavoritePeopleProp).Id;
            using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
            {
                var FavEmails = from i in context.people where i.id.ToString() == Id select i;
                foreach (var objlist in FavEmails)
                {
                    if (objlist.mobile == "" && objlist.home == "" && objlist.mwork == "")
                        check = true;

                }
            }
            if (check == true)
            {
                MessageBoxResult AddContact = MessageBox.Show("The contact has changed click OK to select the contact from contacts", "Import Contact", MessageBoxButton.OKCancel);
                if (AddContact == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/Views/FavoritePeople/contacts.xaml?PId=" + Id, UriKind.Relative));
                    App.navigationstring = "";

                }
                else
                {
                }
            }
            lbxFavoritePeople.SelectedIndex = -1;
        }

        private void message_click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxQuickMessages.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                string id = (selectedListBoxItem.Content as QuickMessageProp).Id;
                NavigationService.Navigate(new Uri("/Views/FavoritePeople/SelectLocation.xaml?Id=" + id + " &type=message", UriKind.Relative));
                App.navigationstring = "";
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  message_click  event In MainPage.xaml page", ex);
            }
        }

        private void peoplechangeLocation_click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxFavoritePeople.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                string id = (selectedListBoxItem.Content as FavoritePeopleProp).Id;
                NavigationService.Navigate(new Uri("/Views/FavoritePeople/SelectLocation.xaml?Id=" + id + " &type=people", UriKind.Relative));
                App.navigationstring = "";
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  peoplechangeLocation_click  event In MainPage.xaml page", ex);
            }
        }

        private void linkschangelocation_click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxQuickLinks.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                string id = (selectedListBoxItem.Content as QuickLinkProp).Id;
                NavigationService.Navigate(new Uri("/Views/FavoritePeople/SelectLocation.xaml?Id=" + id + " &type=link", UriKind.Relative));
                App.navigationstring = "";
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  linkschangelocation_click  event In MainPage.xaml page", ex);
            }
        }

        private void todochangeLocation_click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxToDoList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                string id = (selectedListBoxItem.Content as ToDoListProper).Id;
                NavigationService.Navigate(new Uri("/Views/FavoritePeople/SelectLocation.xaml?Id=" + id + " &type=todo", UriKind.Relative));
                App.navigationstring = "";
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  todochangeLocation_click  event In MainPage.xaml page", ex);
            }
        }

        private void imghelp_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Help/HelpMenu.xaml", UriKind.Relative));
            App.navigationstring = "";
        }

        private void CurrentLocation_Click(object sender, RoutedEventArgs e)
        {
            string id = "";
            try
            {
                IsolatedSettings.saveSettings("GeoLocationStatus1", "false");
                ListBoxItem selectedListBoxItem = this.lbxAddresslist.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                id = (selectedListBoxItem.Content as AddressProp).Id;
                IsolatedSettings.saveSettings("DefaultPlace", id);
                LoadMethods();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  CurrentLocation_Click  event In MainPage.xaml page", ex);
            }
        }

        private void MenuItemlinkedit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxQuickLinks.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                LId = (selectedListBoxItem.Content as QuickLinkProp).Id;
                NavigationService.Navigate(new Uri("/Views/Links/AddLinks.xaml?linkid=" + LId, UriKind.Relative));
                App.navigationstring = "";
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  MenuItemlinkedit_Click  event In MainPage.xaml page", ex);
            }
        }
    }
}



